JavaScript syntax
part 51/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
this.pyz = function() { return this.prefix + "Z"; };
}
this.m1 = px;
return this;
}
const foo1 = new Foo(1);
const foo2 = new Foo(0);
foo2.prefix = "b-";
console.log("foo1/2 " + foo1.pyz() + foo2.pyz());
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
const baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
console.log("m1/m3/m4 " + foo1.m1() + foo1.m3() + baz.m4());
// m1/m3/m4 a-X a-X c-X
foo1.m2(); // Throws an exception, because foo1.m2 does not exist.
Constructors
Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.
Example: Manipulating an object:
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
this.attributeB = attributeB;
}
MyObject.staticC = "blue"; // On MyObject Function, not object
console.log(MyObject.staticC); // blue
const object = new MyObject('red', 1000);
console.log(object.attributeA); // red
console.log(object.attributeB); // 1000
console.log(object.staticC); // undefined
object.attributeC = new Date(); // add a new property
delete object.attributeB; // remove a property of object
console.log(object.attributeB); // undefined
The constructor itself is referenced in the object's prototype's constructor slot. So,
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────